#ifndef _KEYOP_H_
#define _KEYOP_H_
#include "ET199_32.h"

#define  encodestring "wjblovewwqwwqwjb"

__inline void Encode(const char *keyCode, char *dstCode)
{
	char *keystring = encodestring;
	if(keyCode == NULL || dstCode == NULL){
		return;
	}
	int keylen = strlen(keyCode);
	char *tmpCode = dstCode;
	for(int i = 0; i < keylen; i++){
		*tmpCode = *(keyCode + i);
		tmpCode++;
		*tmpCode = rand() % 128;
		tmpCode++;
	}
	keylen *= 2;
	for(int i = 0; i < keylen; i++){
		*(dstCode + i) = *(dstCode + i)^*(keystring + i);
	}
}

__inline void Decode(const char *keyCode, char *dstCode)
{
	char *keystring = encodestring;
	char tmpKeyCode[20] = {0};
	if(keyCode == NULL || dstCode == NULL){
		return;
	}
	strcpy(tmpKeyCode, keyCode);
	int keylen = strlen(tmpKeyCode);
	for(int i = 0; i < keylen; i++){
		*(tmpKeyCode + i) = *(tmpKeyCode + i)^*(keystring + i);
	}
	char *tmpCode = dstCode;
	keylen = keylen / 2 + keylen % 2;
	for(int i = 0; i < keylen; i++){
		*tmpCode = *(tmpKeyCode + i * 2);
		tmpCode++;
	}
	keylen *= 2;
}

__inline int  initCtxDeviceList( PET_CONTEXT &pContextList)
{
	DWORD dwCtxListSize = 0 ;
	DWORD dwResult = 0 ;

	if ( pContextList != NULL ) {
		free( pContextList ) ;
		pContextList = NULL ;
	}

	dwResult = ETEnum(NULL, &dwCtxListSize);
	if (dwResult != 0 && dwResult != ET_E_INSUFFICIENT_BUFFER) {
		printf("Enumerate device failed! <error code: 0x%08x>\n", dwResult);
		return -1;
	}

	if (0 == dwCtxListSize) {
		printf("No device present!\n");
		return 0;
	}


	pContextList = (ET_CONTEXT*)malloc(dwCtxListSize * sizeof(ET_CONTEXT) );
	if (NULL == pContextList) {
		printf("malloc failed! \n");
		return -1;
	}

	dwResult = ETEnum(pContextList, &dwCtxListSize);
	if (0 != dwResult) {
		printf("Enumerate device failed with error code:%d\n",dwResult);
		free( pContextList ) ;
		pContextList = NULL ;
		return -1;
	}
	return  dwCtxListSize;
}

__inline BOOL Authenticate(const char *keyCode)
{
	PET_CONTEXT pContextList = NULL ;	
	ET_CONTEXT * pCtx = NULL;
	int btDeviceNumber = 0;		
	int bIndexDevice  = 0 ;
	DWORD dwResult  = 0;
	char rkeyCode[10] = {0};
	char enkeyCode[10] = {0};
	BOOL bAuth = FALSE;

	Decode(keyCode, rkeyCode);
	btDeviceNumber = initCtxDeviceList( pContextList );

	for ( bIndexDevice = 0 ; bIndexDevice < btDeviceNumber ; bIndexDevice++ ) {

		pCtx = pContextList + bIndexDevice  ;
		dwResult = ETOpen( pCtx );
		if (0 != dwResult) {
			continue;
		}

		DWORD	dwCustomer = 0 ;
		DWORD dwBytesReturned = 0;
		dwResult = ETControl( pCtx , ET_GET_CUSTOMER_NAME, NULL, 0, &dwCustomer, sizeof(DWORD), &dwBytesReturned);
		if (0 != dwResult) {
			ETClose( pCtx );
			continue;
		}
		sprintf(enkeyCode, "%08X", dwCustomer);
		if(!strcmp(enkeyCode, rkeyCode)){
			bAuth = TRUE;
			break;
		}
		ETClose( pCtx );
	}

	if ( NULL != pContextList ) {
		free( pContextList ) ;
		pContextList = NULL ;
	}
	return bAuth;
}

#endif